const express = require("express");
const router = express.Router();
const db = require("../../utils/db");

// 药品销售排行
router.post("/SalesRankingGet", (req, res) => {
  let sql = `  SELECT *, COUNT(m_id) FROM indirect  LEFT JOIN medicinal_information ON indirect.i_m_id=medicinal_information.m_id LEFT JOIN prescription_record ON indirect.i_re_id=prescription_record.re_id GROUP BY m_name ORDER BY (m_price*COUNT(m_id)) DESC;`;
  db.query(sql, (err, data) => {
    if (err) {
      res.send({ error: 1, msg: err });
    } else {
      res.send({ error: 0, data: data });
    }
  });
});

// 药品销售排行
router.post("/MedicineGet", (req, res) => {
  let sql = `SELECT * FROM medicinal_information`;
  db.query(sql, (err, data) => {
    if (err) {
      res.send({ error: 1, msg: err });
    } else {
      res.send({ error: 0, data: data });
    }
  });
});

// 患者信息获取
router.post("/PatientGet", (req, res) => {
  let sql = `SELECT * FROM patient`;
  db.query(sql, (err, data) => {
    if (err) {
      res.send({ error: 1, msg: err });
    } else {
      res.send({ error: 0, data: data });
    }
  });
});

// 查询患者信息
router.post("/checkPatient", (req, res) => {
  const { name } = req.body;
  let sql = `SELECT * FROM patient WHERE s_name LIKE '%${name}%'`;
  db.query(sql, (err, data) => {
    if (err) {
      res.send({ error: 1, msg: err });
    } else {
      res.send({ error: 0, data: data });
    }
  });
});
// 保存
router.post("/RecordKeep", (req, res) => {
  const { re_s_id, re_u_id, i_m_id } = req.body;
  let sql = `INSERT INTO prescription_record VALUES(NULL,'${re_s_id}','${re_u_id}','预防感冒','1002','3',0,'1002','2022-12-12'); `;
  let sql1 = `INSERT INTO indirect VALUES(NULL,'1001','${i_m_id}');`;

  db.query(sql, (err, data) => {
    if (err) {
      res.send({ error: 1, msg: err });
    } else {
      db.query(sql1, (err2, data2) => {
        if (err2) {
          res.send({ error: 1, msg: err2 });
        } else {
          res.send({ error: 0, msg: "保存成功" });
        }
      });
    }
  });
});
// 根据患者id查询医生信息
router.post("/checkDoctorID", (req, res) => {
  const { s_id } = req.body;
  let sql = `SELECT s_u_id FROM patient WHERE s_id=${s_id}`;
  db.query(sql, (err, data) => {
    if (err) {
      res.send({ err, msg: "error" });
    } else {
      res.send({ data: data, msg: "success" });
    }
  });
});
module.exports = router;
